package com.hsyg.netty.server.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 *
 */
public class ServerHandler3 extends
  // ChannelHandlerAdapter {
  ChannelInboundHandlerAdapter {

  private int counter = 0;

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    String body = (String) msg;
    System.out.println("the counter is:" + ++counter + "服务端收到的消息：[" + body + "]");

    body += "$_";
    ByteBuf buffer = Unpooled.copiedBuffer(body.getBytes());
    ctx.writeAndFlush(buffer);
  }


  /**
   * 当发生异常时， 关闭ChannelHandlerContext，释放ChannelHandlerContext相关联的句柄等资源
   *
   * @param ctx
   * @param cause
   * @throws Exception
   */
  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();
    ctx.close();

  }
}
